      
import AuthenticationServices
import Flutter
import UIKit

@UIApplicationMain
class AppDelegate: FlutterAppDelegate, ASAuthorizationControllerDelegate,
  ASAuthorizationControllerPresentationContextProviding
{

  private var appleLoginCompletion: ((Bool) -> Void)?

  override init() {
    super.init()
  }

  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    let controller = window?.rootViewController as! FlutterViewController
    let channel = FlutterMethodChannel(
      name: "com.kudos.ios/appleLogin",
      binaryMessenger: controller.binaryMessenger
    )

    channel.setMethodCallHandler { [weak self] call, result in
      if call.method == "AppleLogin" {
        self?.signInWithApple { success in
          result(success)
        }
      } else {
        result(FlutterMethodNotImplemented)
      }
    }

    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  func signInWithApple(completion: @escaping (Bool) -> Void) {
    if #available(iOS 13.0, *) {
      appleLoginCompletion = completion
      let request = ASAuthorizationAppleIDProvider().createRequest()
      request.requestedScopes = [.fullName, .email]

      let authorizationController = ASAuthorizationController(authorizationRequests: [request])
      authorizationController.delegate = self
      authorizationController.presentationContextProvider = self
      authorizationController.performRequests()
    } else {
      completion(false)
    }
  }

  func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
    return window ?? UIWindow()
  }

  func authorizationController(
    controller: ASAuthorizationController,
    didCompleteWithAuthorization authorization: ASAuthorization
  ) {
    if authorization.credential is ASAuthorizationAppleIDCredential {
      appleLoginCompletion?(true)
    } else {
      appleLoginCompletion?(false)
    }
    appleLoginCompletion = nil
  }

  func authorizationController(
    controller: ASAuthorizationController,
    didCompleteWithError error: Error
  ) {
    appleLoginCompletion?(false)
    appleLoginCompletion = nil
  }
}

    